package idv.kikka.server.handler;

import idv.kikka.server.service.factories.SessionServiceFactory;
import idv.kikka.common.message.ChatRequestMessage;
import idv.kikka.common.message.ChatResponseMessage;
import idv.kikka.server.service.SessionService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class ChatRequestMessageHandler extends SimpleChannelInboundHandler<ChatRequestMessage>{
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        String to = msg.getTo();//获取接受者
        SessionService sessionService= SessionServiceFactory.getSessionService();
        Channel channel = sessionService.getChannel(to);//获取接受者的channel
        //在线
        if(channel!=null){
            //发给别人
            if(ctx.channel()!=channel){
                ctx.writeAndFlush(new ChatResponseMessage(msg.getFrom(), msg.getContent()));
            }
            //给接受者或自己发送发送者传来的消息
            channel.writeAndFlush(new ChatResponseMessage(msg.getFrom(), msg.getContent()));
        }
        //不在线
        else {
            //发送给发送者错误信息
            ctx.writeAndFlush(new ChatResponseMessage(false,"对方用户不存在或不在线！"));
        }
    }
}
